/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * formComponentes.java
 *
 * Created on 02/09/2011, 15:20:49
 */
package javalee.forms;
import java.util.ArrayList;
import java.util.Iterator;
import javalee.util.Uteis;
import javalee.maps.ItensEstrut;
import javalee.dao.ItensEstrutDAO;
import javalee.dao.ProdutoDAO;
import javalee.maps.Produto;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author Danilo
 */
public class formComponentes extends javax.swing.JFrame {

    /** Creates new form formComponentes */
    private ProdutoDAO prodDAO;
    private ItensEstrutDAO itemDAO;
    private Produto pai;
    
    public formComponentes() { 
        initComponents();
        prodDAO = new ProdutoDAO();
        itemDAO = new ItensEstrutDAO();
    }

    public void setProduto(Produto param){
    pai = param;
    }
    private void listaProdutos(){
        if(!Uteis.validaCampoTexto(txtBusca)){
            JOptionPane.showMessageDialog(null,"Campo de pesquisa está incorreto.");
        }
        else{
     //Trago a lista de maquinas do banco
     ArrayList<Produto> lista = prodDAO.consultarSemId(pai.getId(),txtBusca.getText().toString());
     tbProdutos.removeAll();
     
     //Pego o TableModel do componente JTable
     DefaultTableModel tableModel = (DefaultTableModel)tbProdutos.getModel();  
     //Limpo os dados do componente
     tableModel.setNumRows(0);
     
     //Passo pela lista de Maquinas, inserindo no JTable
     for(Iterator<Produto> it = lista.iterator(); it.hasNext();){
        Produto p = (Produto)it.next();
        tableModel.addRow(new Object[]{
            p.getId(),
            p.getDescricao()
        });     
    }   
        }
}
    
   
      
    private void limpaDados(){
        txtBusca.setText("");
        txtQtd.setText("");
    }
    
    private void listaComponentes(){
        btnExcluir.setEnabled(false);
    try{
        ArrayList<ItensEstrut> lista = itemDAO.consultar(pai);
    
     tbComponentes.removeAll();
     
     
     DefaultTableModel tableModel = (DefaultTableModel)tbComponentes.getModel();  
     
     tableModel.setNumRows(0);
     
     
     for(Iterator<ItensEstrut> it = lista.iterator(); it.hasNext();){
        ItensEstrut i = (ItensEstrut)it.next();
        tableModel.addRow(new Object[]{
            i.getProdutoComposto().getId(),
            i.getProdutoComposto().getDescricao(),
            i.getQtdade()
        });     
    }
    }
    catch(Exception e){
        System.out.println(e.toString());
    }   
    }
    
    private void insereItens(){
    int row = tbProdutos.getSelectedRow();
    try{
    DefaultTableModel tableModel = (DefaultTableModel)tbProdutos.getModel();  
    ItensEstrut item = new ItensEstrut();
    item.setProdutoComposto(new Produto(Integer.parseInt(tableModel.getValueAt(row, 0).toString())));
    item.setProduto(pai);
    item.setQtdade(Integer.parseInt(txtQtd.getText()));
   
    itemDAO.cadastrar(item);
    
    limpaDados();
    listaProdutos();
    listaComponentes();
    }
    catch(Exception e){
        System.out.println(e.toString());
    }
    
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbComponentes = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbProdutos = new javax.swing.JTable();
        txtBusca = new javax.swing.JTextField();
        btnOk = new javax.swing.JButton();
        lbQtd = new javax.swing.JLabel();
        btnExcluir = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        txtQtd = new javax.swing.JFormattedTextField(java.text.NumberFormat.getInstance());

        setTitle("Formulario de Componentes");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        tbComponentes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Produto", "Quantidade"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbComponentes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tbComponentesMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tbComponentes);

        tbProdutos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Produto"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(tbProdutos);

        txtBusca.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscaKeyReleased(evt);
            }
        });

        btnOk.setText("Ok");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        lbQtd.setText("Qtdade : ");

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        txtQtd.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtQtdKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtBusca, javax.swing.GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(195, 195, 195)
                        .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 415, Short.MAX_VALUE)
                                .addComponent(lbQtd))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(126, 126, 126)
                                .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(227, 227, 227)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtQtd, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(38, 38, 38)
                        .addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtBusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5)
                        .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 341, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(btnOk)
                                .addComponent(lbQtd)
                                .addComponent(txtQtd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnExcluir)))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
    if(tbComponentes.getSelectedRow()==-1){
        JOptionPane.showMessageDialog(null,"Selecione um item a ser excluído.");
    }
    else{
    int row = tbComponentes.getSelectedRow();
    try{
    DefaultTableModel tableModel = (DefaultTableModel)tbComponentes.getModel();  
    ItensEstrut item = new ItensEstrut();
    item.setProdutoComposto(new Produto(Integer.parseInt(tableModel.getValueAt(row, 0).toString())));
    item.setProduto(pai);
     
    itemDAO.excluir(item);
    
    limpaDados();
    listaProdutos();
    listaComponentes();
    }
    catch(Exception e){
        System.out.println(e.toString());
    }
    // TODO add your handling code here:
    }
}//GEN-LAST:event_btnExcluirActionPerformed

private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
    listaProdutos();
    listaComponentes();
    // TODO add your handling code here:
}//GEN-LAST:event_formWindowActivated

private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
    if(ValidarForm()){
        insereItens();
    }
}//GEN-LAST:event_btnOkActionPerformed

private void txtBuscaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscaKeyReleased
    if(evt.getKeyCode()==10){
        listaProdutos();
    }
    // TODO add your handling code here:
}//GEN-LAST:event_txtBuscaKeyReleased

private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
    dispose();
    // TODO add your handling code here:
}//GEN-LAST:event_btnSairActionPerformed

private void tbComponentesMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbComponentesMouseReleased
if(tbComponentes.getSelectedRow()==-1){
        btnExcluir.setEnabled(false);
    }
else{
        btnExcluir.setEnabled(true);
}
    // TODO add your handling code here:
}//GEN-LAST:event_tbComponentesMouseReleased

private void txtQtdKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtQtdKeyTyped
    if(txtQtd.getText().length() > 4){
        txtQtd.setText(txtQtd.getText().substring(0, 4));
    }
}//GEN-LAST:event_txtQtdKeyTyped
private boolean ValidarForm()
    {
        boolean valido = true;
        
        if(txtQtd.getText().trim().equals(""))
        {
            valido = false;
            JOptionPane.showMessageDialog(null,"Digite a quantidade.");
        }
        else if(Integer.parseInt(txtQtd.getText())<0){
            valido = false;
            JOptionPane.showMessageDialog(null,"Quantidade deve ser maior que zero.");
        }
        if(tbProdutos.getSelectedRow()==-1){
            valido = false;
            JOptionPane.showMessageDialog(null,"Selecione um item.");
        }
       
        return valido;
    }
    
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnOk;
    private javax.swing.JButton btnSair;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbQtd;
    private javax.swing.JTable tbComponentes;
    private javax.swing.JTable tbProdutos;
    private javax.swing.JTextField txtBusca;
    private javax.swing.JFormattedTextField txtQtd;
    // End of variables declaration//GEN-END:variables
}
